#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: pdk_http.py 
@version:
@time: 2022/05/27 
"""
from TapClientCore.T02_tm_api.v2_api.v2_tm import *
from TapException.TM import LoadSchemaError, TapdataNoThisDataSource

TM: [
    Api001Connections,
    Api001DatabaseTypes
] = v2tm

TMP = {"name": "robot_mg",
       "connection_type": "source_and_target",
       "database_type": "MongoDB",
       "pdkHash": "",
       "status": "testing",
       "schema": {},
       "retry": 0,
       "nextRetry": None,
       "response_body": {},
       "project": "",
       "submit": True,
       "pdkType": "pdk",
       "config": {"uri": "test"}}


class PDKHttp:

    # 查询
    @staticmethod
    def _get_connections_by_filter(_filter):
        return TM.pdk_get_connections_by_filter(_filter).get('data')

    # 删除
    @staticmethod
    def _delete_connections(name, _id):
        return TM.pdk_delete_connections_by_name_and_id(name, _id)

    # 创建
    @staticmethod
    def _post_connections(payload):
        return TM.pdk_post_connections(payload)

    # 更新
    @staticmethod
    def _patch_connections(_id, payload):
        return TM.pdk_patch_connections_by_id(_id, payload)

    @staticmethod
    def _pdk_get_database_type():
        return TM.pdk_get_database_type().get('data')

    def pdk_get_pdk_hash(self, _type):
        datatype_list = self._pdk_get_database_type()
        for one in datatype_list:
            if one.get('type') == _type:
                return one.get('pdkHash')
        raise

    def pdk_create_datasource(self, conf):
        name = conf.get('name')
        database_type = conf.get('database_type')
        connection_type = conf.get('connection_type')
        config = conf.get('config')
        pdk_hash = self.pdk_get_pdk_hash(database_type)
        new_conf = {
            'name': name,
            'connection_type': connection_type,
            'database_type': database_type,
            'pdkHash': pdk_hash,
            'config': config
        }
        tmp = TMP.copy()
        tmp.update(new_conf)
        return self._post_connections(tmp)

    def pdk_query_by_name(self, name):
        limit = 20
        skip = 0
        while True:
            _filter = {
                "order": "last_updated DESC",
                "limit": limit,
                "noSchema": 1,
                "skip": skip,
                "where": {}}
            response = self._get_connections_by_filter(_filter)
            items = response.get('items')
            if items:
                for one in items:
                    if one.get('name') == name:
                        return one
            else:
                from TapUtil.logfunc.logger import logger
                logger.fatal(f'not found {name} datasource')
                raise TapdataNoThisDataSource
            skip += limit

    def pdk_patch_datasource(self, name, conf):
        response = self.pdk_query_by_name(name)
        response.update(conf)
        return self._patch_connections(response.get('id'), response)

    def patch_data_source_by_id(self, _id, conf):
        return self._patch_connections(_id, conf)

    def pdk_delete_datasource(self, name):
        _id = self.pdk_query_by_name(name).get('id')
        return self._delete_connections(name, _id)

    def http_loading_schema_by_name(self, name):
        """
        通过数据源名称加载schema http
        :param name:
        :return:
        """
        patch_payload = {"loadCount": 0, "loadFieldsStatus": "loading"}
        patch_result = self.pdk_patch_datasource(name, patch_payload)
        return patch_result

    def ws_loading_schema_by_name(self, name):
        """
        通过数据源名称加载schema ws
        :param name:
        :return:
        """
        response = self.pdk_query_by_name(name)
        datasource_info = response
        from TapClientCore.T05_TM_feature.v2.TMF01_datasource.pdk_ws import ws_load_schema
        ws_result = ws_load_schema(v2tm.ws_uri, datasource_info)
        if not ws_result:
            raise LoadSchemaError
        return ws_result

    def http_try_link_by_name(self, name):
        patch_payload = {"status": "testing"}
        self.pdk_patch_datasource(name, patch_payload)

    def test_datasource_by_name(self, name):
        """
        通过数据源名加载schema
        :param name:
        :return:
        """
        self.http_try_link_by_name(name)
        self.http_loading_schema_by_name(name)
        self.ws_loading_schema_by_name(name)


if __name__ == '__main__':
    T = PDKHttp()
    from TapDataSourceInfo.db_info_pdk import *

    # T.pkd_create_datasource(Mysql.docker_mysql_5733)
    # T.pkd_create_datasource(MongoDB.yun_source)
    # T.pdk_create_datasource(Postgres.postgres_5437)
    print(T.pdk_query_by_name('postgres_5437'))
